<template>
  <van-uploader
    :before-read="beforeRead"
    :after-read="afterRead"
    v-model="fileList"
    :multiple="multiple"
    :accept="accept"
    :capture="capture"
    :max-count="limt"
  />
</template>

<script lang="ts" setup>
const props = defineProps({
  capture: {
    type: String,
    default: 'camera',
  },
  multiple: {
    type: Boolean,
    default: false,
  },
  limt: {
    type: Number,
    default: 1,
  },
  accept: {
    type: String,
    default: "image/jpg, image/png",
  },
});
const { multiple, limt, capture, accept } = toRefs(props);
const fileList = ref([
// { url: 'https://fastly.jsdelivr.net/npm/@vant/assets/leaf.jpeg' },
]);

// 在前置钩子中完成图片压缩功能
function beforeRead(file) {
  console.log("file ======", file);
  let fileSrc = JSON.parse(JSON.stringify(file.type));
  return new Promise((resolve) => {
    let reader = new FileReader();
    let image = new Image();
    if (
      fileSrc == "image/jpeg" ||
      fileSrc == "image/png" ||
      fileSrc == "image/jpg"
    ) {
      image.onload = (imageEvent) => {
        let canvas = document.createElement("canvas");
        let context = canvas.getContext("2d");
        let originWidth = image.width;
        let originHeight = image.height;
        // 最大尺寸限制
        let maxWidth = 1000,
          maxHeight = 1000;
        let targetWidth = originWidth,
          targetHeight = originHeight;
        // 超过1800X1800的限制
        if (originWidth > maxWidth || originHeight > maxHeight) {
          if (originWidth / originHeight > maxWidth / maxHeight) {
            targetWidth = maxWidth;
            targetHeight = Math.round(maxWidth * (originHeight / originWidth));
          } else {
            targetHeight = maxHeight;
            targetWidth = Math.round(maxWidth * (originWidth / originHeight));
          }
        }
        canvas.width = targetWidth;
        canvas.height = targetHeight;
        context.clearRect(0, 0, targetWidth, targetHeight);
        context.drawImage(image, 0, 0, targetWidth, targetHeight);
        let dataUrl = canvas.toDataURL(file.type, 0.8);
        let arr = dataUrl.split(","),
          type = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        const res = new File([u8arr], file.name, { type: file.type });
        resolve(res);
      };
    }

    // 此步骤是必须要返回的新file对象，不可或缺
    reader.onload = (e) => {
      image.src = e.target.result;
    };
    reader.readAsDataURL(file);
  });
}

function afterRead(file) {
  // 此时可以自行将文件上传至服务器
  console.log('图片上传：', file);
}
</script>

<style lang="scss" scoped>
</style>
